﻿using System;
using System.DirectoryServices;
using System.Globalization;
using NAnt.Contrib.Tasks.Web;
using NAnt.Core;
using NAnt.Core.Attributes;

namespace Lean.NantTasks.Deployment
{
    /// <summary>
    /// Based on the the IIS-Tasks of Nant-Contrib this tasks retrieves a single iis-property and stores it as a nant-property of a given name
    /// </summary>
    [TaskName("iisinfo")]
    public class IisInfoTask : WebBase {

        [TaskAttribute("property"), StringValidator(AllowEmpty = false)]
        public string Propertyname { get; set; }
        [TaskAttribute("iisproperty"), StringValidator(AllowEmpty = false)]
        public string IISPropertyname { get; set; }

        protected override void ExecuteTask() {
            Log(Level.Debug, "Retrieving settings of virtual directory '{0}' on '{1}' (website: {2}).",
                this.VirtualDirectory, 
                this.Server,
                this.Website);

            // ensure IIS is available on specified host and port
            this.CheckIISSettings();

            try {
                DirectoryEntry folderRoot = new DirectoryEntry(this.ServerPath);
                folderRoot.RefreshCache();
                DirectoryEntry newVirDir = folderRoot.Children.Find(
                    this.VirtualDirectory, folderRoot.SchemaClassName);

                var value = newVirDir.Properties[IISPropertyname].Value.ToString();
                Log(Level.Debug, IISPropertyname+ ": " + value);
                Properties[Propertyname] = value;


                newVirDir.Close();
                folderRoot.Close();
            } catch (BuildException) {
                // re-throw exception
                throw;
            } catch (Exception ex) {
                throw new BuildException(string.Format(CultureInfo.InvariantCulture,
                                                       "Error retrieving info for virtual directory '{0}' on '{1}' (website: {2}).", 
                                                       this.VirtualDirectory, this.Server, this.Website), Location, ex);
            }
        }
    }
}